package node.decl;

import grammar.Lexer;
import lexical.Key;
import node.Node;
import node.exp.ConstExp;
import symbol.SymbolTable;

import java.util.ArrayList;

public class ConstInitVal implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    private int dim;
    private ConstExp constExp;
    private ArrayList<ConstInitVal> constInitVals = new ArrayList<>();
    private ArrayList<Node> nodes = new ArrayList<>();

    public ConstInitVal(Lexer lexer, SymbolTable table, Node father, int dim) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        this.dim = dim;
        parseConstInitVal();
    }

    private void parseConstInitVal() {
        if (!lexer.isWordType(0, Key.LBRACE)) {
            constExp = new ConstExp(lexer, table, this);
            nodes.add(constExp);
        } else {
            nodes.add(lexer.getCurWord()); // {
            ConstInitVal constInitVal;
            if (!lexer.isWordType(0, Key.RBRACE)) {
                constInitVal = new ConstInitVal(lexer, table, this, dim - 1);
                nodes.add(constInitVal);
                constInitVals.add(constInitVal);
                while (lexer.isWordType(0, Key.COMMA)) {
                    nodes.add(lexer.getCurWord()); // ,
                    constInitVal = new ConstInitVal(lexer, table, this, dim - 1);
                    nodes.add(constInitVal);
                    constInitVals.add(constInitVal);
                }
            }
            nodes.add(lexer.getCurWord()); // }
        }
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<ConstInitVal>\n").toString();
    }

    @Override
    public String genMidCode() {
        return "";
    }

    public int getVal_0() {
        return constExp.getValue();
    }

    public ArrayList<Integer> getVal_1() {
        ArrayList<Integer> val_1 = new ArrayList<>();
        for (ConstInitVal constInitVal:constInitVals) {
            val_1.add(constInitVal.getVal_0());
        }
        return val_1;
    }

    public ArrayList<ArrayList<Integer>> getVal_2() {
        ArrayList<ArrayList<Integer>> val_2 = new ArrayList<>();
        for (ConstInitVal constInitVal:constInitVals) {
            val_2.add(constInitVal.getVal_1());
        }
        return val_2;
    }
}
